/*
 Copyright (C) 2010 Chris Hawkins. All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
 
 * Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.
 
 * Neither the name of the author nor the names of its contributors may be used
 to endorse or promote products derived from this software without specific
 prior written permission.
 
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#import <libkern/OSAtomic.h>
#import "AsdMacro.h"
#import "AsdRequest.h"
#import "AsdNotification.h"
#import "AsdUtil.h"
#import "AsdParseDef.h"

@implementation ASDRqBase
@synthesize sequenceNumber, parser, result, urlRequest, httpResponse, startTime, endTime, connectionError;
@synthesize responseData = responseDataBuf;

#pragma mark -- NSObject standard
+ (NSUInteger)              nextSeqNumber {
    static int32_t nextNumber = ( NSIntegerMin +1);
    return ( OSAtomicIncrement32Barrier( &nextNumber ) + NSIntegerMax);
}
- (id)                      initWithEndpoint: (ASDCfEndpoint*) endpoint_ provider: (NSObject<ASD_SignatureProvider>*) provider_ {
    self = [super init];
    if ( self != nil ) {
        sequenceNumber      = [ASDRqBase nextSeqNumber];
        result              = [ASDSpResult resultPending];    // Singleton - retain ignored
        signatureProvider   = [provider_ retain];
        endpoint            = [endpoint_ retain];
        dictParameters      = [[NSMutableDictionary alloc] initWithCapacity: 20];
    }
    return self;
}
- (void)                    dealloc {
    [endpoint          release];
    [signatureProvider release];
    [parser            release];
    [dictParameters    release];
    
    [signatureSource   release];
    [requestUrl        release];
    [urlRequest        release];
    [httpResponse      release];
    [urlConnection     release];
    [connectionError   release];
    [responseDataBuf   release];
    [startTime         release];
    [endTime           release];
    [super dealloc];
}
/** SimpleDb Operations - override in derived class */
+ (NSString*)               kOperationName {
    return [NSString string];
} 
+ (NSString*)               kNotificationName {
    return [NSString string];
}
+ (ASDPrElementDictionary*) parseElementDictionary {
    return [ASDPrDef dictionaryBase];
}
#pragma mark -- Request Parameter logic
- (void)                    addParameter: (NSString*) parmValue_ key: (NSString*) parmKey_ {
    if ( [result code] == eAsdSpResult_Pending ) {
        [dictParameters setValue: parmValue_ forKey: parmKey_];
    }
}
- (NSString*)               getParameterByKey: (NSString*) parmKey_ {
    return [dictParameters valueForKey: parmKey_];
}
+ (NSString*)               sortedQueryString: (NSDictionary*) dictParameters_ encode: (BOOL) doEncode_ {
    NSMutableString *queryString = [[NSMutableString alloc] initWithCapacity: ( [dictParameters_ count] * 50 )];
    NSArray         *sortedKeys  = [[[dictParameters_ allKeys] sortedArrayUsingSelector: @selector( compare: )] retain];
    BOOL             firstPass   = TRUE;
    for ( NSString *key in sortedKeys ) {
        NSString *value    = [dictParameters_ valueForKey: key];
        if ( firstPass ) {
            firstPass = FALSE;
        } else {
            [queryString appendString: @"&"];
        }
        [queryString appendString: key];
        [queryString appendString: @"="];
        if ( doEncode_ ) {
            NSString *encode  = [[ASDSpUtil urlEncode: value] retain];
            [queryString appendString: encode];
            [encode release];
        } else {
            [queryString appendString: value];            
        }
    }
    [sortedKeys release];
    return [queryString autorelease];
}
#pragma mark -- Parser accessor (not allowed while operation is running)
- (BOOL)                    setParser: (ASDPrBase*) parser_ {
    BOOL updated = ( [result code] != eAsdSpResult_Running );
    if ( updated ) {
        mASDreleaseNil( parser );
        if ( parser_ != nil ) {
            parser = [parser_ retain];
        }
    }
    return updated;
}

@end
